import React from 'react';
import { Table, Button, Select, message } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import { PlusOutlined, CaretDownOutlined, DeleteOutlined } from '#/utils/antdIcons';
import { TRDefault } from '@/components';

import {
  getPathTableColumnsConfig,
  calculateNewRowLossPrice,
  calculateModifyRowLossPrice,
  calculateRemoveRowLossPrice,
  calculateAllLossPirce,
  castPathInfoToTableObj,
} from '../helper';
import { fetchDimLinePaths } from '../service';
import styles from './index.less';

const { Option } = Select;
const PathTableCalculate = ({ errorFetchData }, ref) => {
  // 暴露给父组件的方法
  React.useImperativeHandle(ref, () => ({
    // 清理路线表格
    clearImmediate: () => {
      setPaths([castPathInfoToTableObj(provincePaths, 0)]);
    },
    // 获取路线表格内容
    getPaths: () => paths,
    setCondition: (condition) => {
      setCalculateCondition(condition);
    },
  }));

  // mock 线路数组
  const [paths, setPaths] = React.useState([]);
  // 路线基本信息数组
  const [provincePaths, setProvincePaths] = React.useState([]);
  const [otherPaths, setOtherPaths] = React.useState([]);
  // 计算网损的价格、正算反算标识初始化
  const [calculateCondition, setCalculateCondition] = React.useState({ price: 0.0, type: 'send' });
  // table加载框
  const [loading, setLoading] = React.useState(false);

  // 获取全国线路信息
  // todo：接口调用
  React.useEffect(() => {
    setLoading(true);
    fetchDimLinePaths().then(({ statusCode, provincePathList, otherPathList, message }) => {
      setLoading(false);
      if (statusCode != 1000) {
        errorFetchData(message);
        return;
      }
      setProvincePaths(provincePathList);
      setOtherPaths(otherPathList);
    });
  }, []);
  // 初始化计算表格的值
  React.useEffect(() => {
    provincePaths && provincePaths.length && setPaths([castPathInfoToTableObj(provincePaths, 0)]);
  }, [provincePaths]);
  // 监听价格变化，重新计算每一行的网损折价
  React.useEffect(() => {
    paths && paths.length && setPaths(calculateAllLossPirce(calculateCondition, paths));
  }, [calculateCondition]);

  /**
   * 线路名称列渲染
   * @param {String} text 当前列绑定字段的值
   * @param {Object} record 当前行的所有字段的对象
   * @param {Number} index 第几行，从0开始
   * @returns
   */
  const pathColumnRender = (text, record, index) => {
    return (
      <Select
        showSearch
        dropdownClassName={styles.calculateSelect}
        defaultValue={text}
        bordered={false}
        suffixIcon={<CaretDownOutlined style={{ color: '#D8D8D8' }} />}
        onChange={(value) => rowSelectChange(value, index)}
        filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        notFoundContent={<TRDefault type="emptysm" />}
      >
        {index == 0
          ? provincePaths.map((baseInfo) => (
              <Option key={baseInfo.id + 10000} value={baseInfo.lineName}>
                {baseInfo.lineName}
              </Option>
            ))
          : otherPaths.map((baseInfo) => (
              <Option key={baseInfo.id + 10000} value={baseInfo.lineName}>
                {baseInfo.lineName}
              </Option>
            ))}
      </Select>
    );
  };
  /**
   * 操作列渲染
   * @returns
   */
  const operateColumnRender = (text, record, index) => {
    if (index == 0) {
      return '';
    }
    return (
      <Button
        type="primary"
        shape="circle"
        danger
        onClick={() => deleteRowClick(index)}
        icon={<DeleteOutlined />}
      />
    );
  };

  /**
   * 删除单行表格
   * @param {Number} index  行索引，从0开始
   */
  const deleteRowClick = (index) => {
    if (index == 0) {
      message.warn('省份路线信息不允许删除，请直接修改');
      return;
    }
    let newPaths = paths.filter((item, i) => i != index);
    setPaths(calculateRemoveRowLossPrice(calculateCondition, index, newPaths));
  };

  /**
   * 行中路线选择改变时
   * @param {String} value 选择的路线
   * @param {Number} index 表格行索引
   */
  const rowSelectChange = (value, index) => {
    let targetPaths = index == 0 ? provincePaths : otherPaths;
    paths[index] = castPathInfoToTableObj(
      targetPaths,
      targetPaths.findIndex((item) => item.lineName == value),
    );
    setPaths(calculateModifyRowLossPrice(calculateCondition, index, paths));
  };

  /**
   * 点击新建路线
   */
  const createRowClick = () => {
    // 初始化新行数据并添加
    let newArr = [...paths, castPathInfoToTableObj(otherPaths, 0)];
    // 重新计算网损折价
    setPaths(calculateNewRowLossPrice(calculateCondition, newArr));
  };
  /**
   * 底部新建渲染
   */
  const footerRender = () => {
    return (
      <div className={styles.createRow}>
        <Button type="link" onClick={createRowClick} icon={<PlusOutlined />}>
          新建
        </Button>
      </div>
    );
  };

  // 获取table的列配置
  const columnsConfig = getPathTableColumnsConfig(pathColumnRender, operateColumnRender);
  return (
    <div className={styles.container}>
      <Table
        loading={loading}
        columns={columnsConfig}
        locale={tableLocale}
        dataSource={paths}
        pagination={false}
        bordered
        size="small"
        footer={footerRender}
      />
    </div>
  );
};

export default React.forwardRef(PathTableCalculate);
